<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>音频录制器</title>

    <!-- 添加MediaDevices polyfill -->
    <script src="https://cdn.jsdelivr.net/npm/webrtc-adapter@7.7.0/dist/adapter.min.js"></script>

    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 600px;
            margin: 50px auto;
            padding: 20px;
            text-align: center;
        }

        button {
            padding: 10px 20px;
            margin: 10px;
            font-size: 16px;
            cursor: pointer;
            border: none;
            border-radius: 5px;
            color: white;
            transition: all 0.3s;
        }

        #startBtn {
            background-color: #28a745;
        }

        #pauseBtn {
            background-color: #ffc107;
            color: #000;
        }

        #resumeBtn {
            background-color: #17a2b8;
        }

        #stopBtn {
            background-color: #dc3545;
        }

        #saveBtn {
            background-color: #007bff;
        }

        button:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
            color: white;
        }

        button:hover:not(:disabled) {
            opacity: 0.8;
            transform: translateY(-2px);
        }

        #status {
            margin: 20px 0;
            padding: 15px;
            border-radius: 8px;
            font-weight: bold;
        }

        .ready {
            background-color: #e8f5e8;
            color: #2e7d32;
            border: 2px solid #2e7d32;
        }

        .recording {
            background-color: #fff3cd;
            color: #856404;
            border: 2px solid #ffc107;
        }

        .paused {
            background-color: #d1ecf1;
            color: #0c5460;
            border: 2px solid #17a2b8;
        }

        .error {
            background-color: #f8d7da;
            color: #721c24;
            border: 2px solid #dc3545;
        }

        #timer {
            font-size: 32px;
            margin: 20px 0;
            font-weight: bold;
            color: #333;
        }

        .recording-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            background-color: #dc3545;
            border-radius: 50%;
            margin-right: 8px;
            animation: pulse 1.5s infinite;
        }

        .paused-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            background-color: #ffc107;
            border-radius: 50%;
            margin-right: 8px;
        }

        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }

        .controls {
            display: flex;
            justify-content: center;
            flex-wrap: wrap;
            gap: 10px;
            margin: 20px 0;
        }

        .control-group {
            margin: 10px 0;
        }

        .recording-info {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            margin: 15px 0;
            text-align: left;
        }
    </style>
</head>
<body>
    <h1>🎤 高级音频录制器</h1>
    <p>支持暂停/继续功能的音频录制</p>

    <div class="controls">
        <button id="startBtn">开始录音</button>
        <button id="pauseBtn" disabled>暂停</button>
        <button id="resumeBtn" disabled>继续</button>
        <button id="stopBtn" disabled>停止</button>
        <button id="saveBtn" disabled>保存为AAC</button>
    </div>

    <div id="status" class="ready">
        <span id="statusIcon">✅</span>
        <span id="statusText">准备就绪</span>
    </div>

    <div id="timer">00:00</div>

    <div class="recording-info" id="recordingInfo" style="display: none;">
        <h3>录制信息</h3>
        <p>总时长: <span id="totalDuration">00:00</span></p>
        <p>有效录制: <span id="actualDuration">00:00</span></p>
        <p>暂停次数: <span id="pauseCount">0</span></p>
    </div>

    <script>
        let mediaRecorder;
        let audioChunks = [];
        let timerInterval;
        let seconds = 0;
        let actualRecordingSeconds = 0;
        let isPaused = false;
        let pauseCount = 0;
        let pauseStartTime = 0;

        function updateTimer() {
            seconds++;
            if (!isPaused) {
                actualRecordingSeconds++;
            }
            updateTimerDisplay();
        }

        function updateTimerDisplay() {
            const totalMinutes = Math.floor(seconds / 60);
            const totalSeconds = seconds % 60;
            const actualMinutes = Math.floor(actualRecordingSeconds / 60);
            const actualSeconds = actualRecordingSeconds % 60;

            document.getElementById('timer').textContent =
                `${totalMinutes.toString().padStart(2, '0')}:${totalSeconds.toString().padStart(2, '0')}`;

            document.getElementById('totalDuration').textContent =
                `${totalMinutes.toString().padStart(2, '0')}:${totalSeconds.toString().padStart(2, '0')}`;

            document.getElementById('actualDuration').textContent =
                `${actualMinutes.toString().padStart(2, '0')}:${actualSeconds.toString().padStart(2, '0')}`;
        }

        function startTimer() {
            seconds = 0;
            actualRecordingSeconds = 0;
            pauseCount = 0;
            updateTimerDisplay();
            timerInterval = setInterval(updateTimer, 1000);
            document.getElementById('recordingInfo').style.display = 'block';
            document.getElementById('pauseCount').textContent = pauseCount;
        }

        function stopTimer() {
            clearInterval(timerInterval);
        }

        function updateStatus(message, type) {
            const statusElement = document.getElementById('status');
            const statusText = document.getElementById('statusText');
            const statusIcon = document.getElementById('statusIcon');

            statusElement.className = type;
            statusText.textContent = message;

            // 更新状态图标
            switch(type) {
                case 'ready':
                    statusIcon.textContent = '✅';
                    break;
                case 'recording':
                    statusIcon.textContent = '🔴';
                    break;
                case 'paused':
                    statusIcon.textContent = '⏸️';
                    break;
                case 'error':
                    statusIcon.textContent = '❌';
                    break;
            }
        }

        function updateButtonStates(state) {
            const states = {
                'idle': { start: false, pause: true, resume: true, stop: true, save: true },
                'recording': { start: true, pause: false, resume: true, stop: false, save: true },
                'paused': { start: true, pause: true, resume: false, stop: false, save: true },
                'stopped': { start: false, pause: true, resume: true, stop: true, save: false }
            };

            const buttonState = states[state];
            document.getElementById('startBtn').disabled = buttonState.start;
            document.getElementById('pauseBtn').disabled = buttonState.pause;
            document.getElementById('resumeBtn').disabled = buttonState.resume;
            document.getElementById('stopBtn').disabled = buttonState.stop;
            document.getElementById('saveBtn').disabled = buttonState.save;
        }

        document.getElementById('startBtn').onclick = async () => {
            try {
                // 请求麦克风权限
                const stream = await navigator.mediaDevices.getUserMedia({
                    audio: {
                        echoCancellation: true,
                        noiseSuppression: true,
                        sampleRate: 44100,
                        channelCount: 1
                    }
                });

                // 创建MediaRecorder
                mediaRecorder = new MediaRecorder(stream, {
                    mimeType: 'audio/webm;codecs=opus'
                });

                audioChunks = [];

                // 处理数据可用事件
                mediaRecorder.ondataavailable = (event) => {
                    if (event.data.size > 0 && !isPaused) {
                        audioChunks.push(event.data);
                        console.log(`采集到音频数据: ${event.data.size} 字节`);
                    }
                };

                // 处理录音停止事件
                mediaRecorder.onstop = () => {
                    const audioBlob = new Blob(audioChunks, { type: 'audio/webm' });
                    console.log(`最终音频大小: ${audioBlob.size} 字节, 片段数: ${audioChunks.length}`);

                    updateStatus('录音完成，可以保存', 'ready');
                    updateButtonStates('stopped');
                    stopTimer();

                    // 停止所有轨道
                    stream.getTracks().forEach(track => track.stop());
                };

                // 处理暂停事件
                mediaRecorder.onpause = () => {
                    console.log('录音已暂停');
                    updateStatus('录音已暂停', 'paused');
                    updateButtonStates('paused');
                };

                // 处理继续事件
                mediaRecorder.onresume = () => {
                    console.log('录音继续');
                    updateStatus('录音中...', 'recording');
                    updateButtonStates('recording');
                };

                // 开始录音
                mediaRecorder.start(1000); // 每1秒收集一次数据

                // 更新UI状态
                updateStatus('录音中...', 'recording');
                updateButtonStates('recording');

                // 开始计时
                startTimer();
                isPaused = false;

            } catch (error) {
                console.error('无法访问麦克风:', error);
                updateStatus('错误: ' + error.message, 'error');
            }
        };

        document.getElementById('pauseBtn').onclick = () => {
            if (mediaRecorder && mediaRecorder.state === 'recording') {
                mediaRecorder.pause();
                isPaused = true;
                pauseCount++;
                document.getElementById('pauseCount').textContent = pauseCount;
                console.log(`第 ${pauseCount} 次暂停`);
            }
        };

        document.getElementById('resumeBtn').onclick = () => {
            if (mediaRecorder && mediaRecorder.state === 'paused') {
                mediaRecorder.resume();
                isPaused = false;
            }
        };

        document.getElementById('stopBtn').onclick = () => {
            if (mediaRecorder && (mediaRecorder.state === 'recording' || mediaRecorder.state === 'paused')) {
                mediaRecorder.stop();
                updateStatus('正在处理音频...', 'ready');
            }
        };

        document.getElementById('saveBtn').onclick = async () => {
            if (audioChunks.length === 0) {
                updateStatus('没有录音数据', 'error');
                return;
            }

            const audioBlob = new Blob(audioChunks, { type: 'audio/webm' });
            const formData = new FormData();
            formData.append('audio', audioBlob, 'recording.webm');

            // 添加录制信息
            formData.append('total_duration', seconds);
            formData.append('actual_duration', actualRecordingSeconds);
            formData.append('pause_count', pauseCount);

            updateStatus('正在转换和下载...', 'ready');

            try {
                const response = await fetch('/recordingMinutes/convert_to_aac_save', {
                    method: 'POST',
                    body: formData
                });

                if (response.ok) {
                    const blob = await response.blob();

                    // 创建下载链接
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
                    a.download = `recording_${timestamp}.aac`;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    window.URL.revokeObjectURL(url);

                    const infoMessage = `录音保存成功！
总时长: ${Math.floor(seconds/60)}分${seconds%60}秒
有效录制: ${Math.floor(actualRecordingSeconds/60)}分${actualRecordingSeconds%60}秒
暂停次数: ${pauseCount}`;

                    updateStatus('文件已保存！', 'ready');
                    alert(infoMessage);

                } else {
                    const errorText = await response.text();
                    updateStatus('转换失败: ' + errorText, 'error');
                }
            } catch (error) {
                console.error('保存失败:', error);
                updateStatus('网络错误: ' + error.message, 'error');
            }
        };

        // 初始化按钮状态
        updateButtonStates('idle');

        // 检查浏览器支持
        if (!navigator.mediaDevices) {
                //issues.push('navigator.mediaDevices 不支持');
                updateStatus('navigator.mediaDevices 不支持', 'error');
            }

        if (!navigator.mediaDevices.getUserMedia) {
            //issues.push('getUserMedia 不支持');
            updateStatus('getUserMedia 不支持', 'error');
        }

        // 检查浏览器支持
        if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
            updateStatus('您的浏览器不支持音频录制', 'error');
            document.getElementById('startBtn').disabled = true;
        }

        // 检查MediaRecorder是否支持暂停/继续
        if (typeof MediaRecorder === 'undefined' ||
            !MediaRecorder.prototype ||
            typeof MediaRecorder.prototype.pause !== 'function') {
            console.warn('当前浏览器不支持MediaRecorder的暂停功能');
            document.getElementById('pauseBtn').style.display = 'none';
            document.getElementById('resumeBtn').style.display = 'none';
        }
    </script>
</body>
</html>

